package v1

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"maya-service/bll"
	"maya-service/constant"
	"maya-service/model"
	"maya-service/model/po"
	"maya-service/server/web/middleware"
	"maya-service/utils"
	"maya-service/utils/request"
)

var QuanxiQuestion = &quanxiQuestion{}

func init() {
	fmt.Println("############################ quanxi_question init")
	RegisterRouter(QuanxiQuestion)
}

type quanxiQuestion struct{}

// Init
func (a *quanxiQuestion) Init(r *gin.RouterGroup) {
	fmt.Println("############################ quanxi_question init group")
	g := r.Group("/quanxiQuestion", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/update", a.update)
		g.POST("/list", a.list)
		g.POST("/delete", a.delete)
		g.POST("/detail", a.find)
		g.POST("/ai", a.ai)
	}
}

// create
func (a *quanxiQuestion) create(c *gin.Context) {
	var (
		in  = &po.QuanxiQuestionCreateReq{}
		err error
		id  int64
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	// 获取用户ID
	userId, err := request.GetUserId(c.Request.Context())
	if err != nil {
		c.Error(err)
		return
	}
	in.UserId = userId

	// 问题检测
	/*find, _ := bll.QuanxiQuestion.Find(c.Request.Context(), &model.QuanxiQuestionInfoRequest{Qustion: in.Question})
	if find != nil && find.Id > 0 {
		c.Error(fmt.Errorf("quanxi question already exists"))
		return
	}*/

	// 投放的时候随机绑定苹果
	fruits, _ := utils.GetRandomStrings(constant.GetFruits(), len(in.Options))
	for i := 0; i < len(in.Options); i++ {
		in.Options[i].Fruit = fruits[i]
	}

	data, _ := json.Marshal(in.Options)
	if id, err = bll.QuanxiQuestion.Create(c.Request.Context(), &model.QuanxiQuestionCreateRequest{
		UserId:   in.UserId,
		Question: in.Question,
		Options:  string(data),
		Type:     in.Type,
	}); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, struct {
		ID int64 `json:"id"`
	}{ID: id})
}

// update
func (a *quanxiQuestion) update(c *gin.Context) {
	var (
		in  = &model.QuanxiQuestionUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.QuanxiQuestion.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// list
func (a *quanxiQuestion) list(c *gin.Context) {
	var (
		in  = &model.QuanxiQuestionListRequest{}
		out = &model.QuanxiQuestionListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.QuanxiQuestion.List(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}

	ret := &po.QuanxiQuestionListResponse{
		Total: out.Total,
		List:  nil,
	}

	for i := 0; i < len(out.List); i++ {
		var options []*po.QuanxiOption
		json.Unmarshal([]byte(out.List[i].Options), &options)
		ret.List = append(ret.List, &po.QuanxiQuestionInfoRsp{
			Id:       out.List[i].Id,
			Question: out.List[i].Question,
			Options:  options,
			Type:     out.List[i].Type,
			Created:  out.List[i].CreatedAt,
			Updated:  out.List[i].UpdatedAt,
		})
	}

	utils.ResponseOk(c, ret)
}

// list
func (a *quanxiQuestion) find(c *gin.Context) {
	var (
		in  = &model.QuanxiQuestionInfoRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	var out *model.QuanxiQuestionInfo
	if out, err = bll.QuanxiQuestion.Find(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	var options []*po.QuanxiOption
	json.Unmarshal([]byte(out.Options), &options)
	utils.ResponseOk(c, &po.QuanxiQuestionInfoRsp{
		Id:       out.Id,
		Question: out.Question,
		Options:  options,
		Type:     out.Type,
		Created:  out.CreatedAt,
		Updated:  out.UpdatedAt,
	})
}

// delete
func (a *quanxiQuestion) delete(c *gin.Context) {
	var (
		in  = &model.QuanxiQuestionDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.QuanxiQuestion.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

func (a *quanxiQuestion) ai(c *gin.Context) {
	url := "https://api.coze.cn/v1/workflow/run"

	type Body struct {
		WorkflowId string `json:"workflow_id"`
		Input      string `json:"input"`
	}

	sendData, _ := json.Marshal(&Body{WorkflowId: "7433999366543917075", Input: "请给我 3个不同的大家最近会占卜的问题，给我输出3个问句"})
	rsp, err := request.DoRequest("POST", url, string(sendData), map[string]string{
		"Authorization": "Bearer pat_5Do9945xBDp7pBeX7X8DheznuEpm8ijL41aKRp60sbWnJeP2MbmHce2GUZJnyYmu",
	})
	if err != nil {
		c.Error(err)
		return
	}

	// Response 表示 API 返回的整体结构
	type Response struct {
		Code     int    `json:"code"`      // 返回代码
		Cost     string `json:"cost"`      // 成本信息
		Data     string `json:"data"`      // 数据部分，通常是 JSON 字符串
		DebugURL string `json:"debug_url"` // 调试 URL
		Msg      string `json:"msg"`       // 消息
		Token    int    `json:"token"`     // 令牌
	}

	// DataContent 表示 Data 字段中的内容
	type DataContent struct {
		Title1 string `json:"title1"` // 问题 1
		Title2 string `json:"title2"` // 问题 2
		Title3 string `json:"title3"` // 问题 3
	}

	respData := &Response{}
	json.Unmarshal([]byte(rsp), respData)

	data := &DataContent{}
	json.Unmarshal([]byte(respData.Data), &data)

	utils.ResponseOk(c, struct {
		List []string `json:"list"`
	}{
		List: []string{
			fmt.Sprintf("1.%v", data.Title1),
			fmt.Sprintf("2.%v", data.Title2),
			fmt.Sprintf("3.%v", data.Title3),
		},
	})
	return
}
